package org.nobody.mallb2c.mallorder.listener;

import com.rabbitmq.client.Channel;
import org.nobody.mallb2c.mallorder.entity.OrderEntity;
import org.nobody.mallb2c.mallorder.service.OrderService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author 3489309323@qq.com
 * @create 2020-09-26-12:05
 */
@RabbitListener(queues = "order.release.order.queue")
@Service
public class OrderCloseListener {
  @Autowired
  OrderService orderService;

  /**
   * 超过指定时间未付款,需要自动关单
   * @param entity
   * @param channel
   * @param message
   * @throws IOException
   */
  @RabbitHandler
  public void listener(OrderEntity entity, Channel channel, Message message) throws IOException {
    System.out.println("收到过期的订单信息, 准备关闭订单: " + entity.getOrderSn());
    try {
      orderService.closeOrder(entity);

      //todo 手动调用支付宝收单:
      //https://opendocs.alipay.com/apis/api_1/alipay.trade.close

      channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    } catch (Exception e) {
      channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
    }
  }
}
